package com.honkentuber.chat;

import org.json.simple.JSONObject;

import com.google.appengine.api.datastore.KeyFactory;
import com.honkentuber.AppContext;

public class NewRoomServlet extends ChatBaseServlet {
  private static final long serialVersionUID = 3160171517137130469L;

  private Room newRoom(AppContext ctx) {
    ChatContext chatCtx = (ChatContext) ctx;
    ChatDatabase db = chatCtx.getChatDb();
    return db.createRoom(ctx.user, ctx.req.getParameter("name"));
  }

  @Override
  protected String newJspResponse(AppContext ctx) {
    Room room = newRoom(ctx);
    String response = room != null ? ("New room created with ID: " + KeyFactory
        .keyToString(room.getKey())) : "fail";
    ctx.req.setAttribute("response", response);
    return "/response.jsp";
  }

  @Override
  @SuppressWarnings("unchecked")
  protected JSONObject newJsonResponse(AppContext ctx) {
    Room room = newRoom(ctx);
    JSONObject jsonResponse = new JSONObject();
    if (room == null) {
      jsonResponse.put("status", "fail");
    } else {
      jsonResponse.put("status", "success");
      jsonResponse.put("roomKey", KeyFactory.keyToString(room.getKey()));
    }
    return jsonResponse;
  }

}